package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"
	"hema-fresh/models/cache"
	"hema-fresh/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *hemarpc.ProductListRequest) (*hemarpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	offset, size := mysql.GetProductList(int(in.Page), int(in.Size))
	var list []mysql.Product
	key := fmt.Sprintf("productList_%d_%d_%s", offset, size, in.Title)

	result, _ := cache.RDB.Get(l.ctx, key).Result()
	if result == "" {
		tx := mysql.DB.Debug().Offset(offset).Limit(size)

		if in.Title != "" {
			tx.Where("name like ?", "%"+in.Title+"%")
		}

		tx.Find(&list)
		marshal, _ := json.Marshal(list)
		cache.RDB.Set(l.ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	var lists []*hemarpc.ProductList
	for _, product := range list {
		productList := hemarpc.ProductList{
			Name:         product.Name,
			Price:        float32(product.Price),
			Stock:        int64(product.Stock),
			CategoryName: product.CategoryName,
		}
		lists = append(lists, &productList)
	}
	return &hemarpc.ProductListResponse{
		List: lists,
	}, nil
}
